<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { riderApi } from "@/api/rider";
import type { VehicleType } from "@/types/rider";

const router = useRouter();

const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  realName: "",
  idCard: "",
  phone: "",
  vehicleType: "" as VehicleType | "",
  vehicleNumber: "",
  idCardFront: "",
  idCardBack: "",
});

const registerRules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        let len = 0;
        for (let i = 0; i < value.length; i++) {
          const code = value.charCodeAt(i);
          if (code >= 0x4e00 && code <= 0x9fa5) {
            len += 1; // 中文
          } else if (
            (code >= 0x30 && code <= 0x39) || // 数字
            (code >= 0x41 && code <= 0x5a) || // 大写字母
            (code >= 0x61 && code <= 0x7a)
          ) {
            len += 0.5; // 英文或数字
          } else {
            // 其他字符不计入长度
          }
        }
        if (len < 3 || len > 7) {
          callback(
            new Error("用户名长度需为3~7个字符（中文算1，英文/数字算0.5）")
          );
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 8,
      max: 18,
      message: "密码长度8-18位，需包含英文和数字",
      trigger: "blur",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,18}$/.test(value)) {
          callback(new Error("密码需包含英文和数字，长度8-18位"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  realName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度应为2-10个字符", trigger: "blur" },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  vehicleType: [
    { required: true, message: "请选择配送工具", trigger: "blur" },
  ],
  vehicleNumber: [
    { required: true, message: "请输入车辆牌照", trigger: "blur" },
  ],
});

const registerFormRef = ref<FormInstance>();
const loading = ref(false);

// 车辆类型选项
const vehicleTypes = [
  { label: "自行车", value: "BIKE" },
  { label: "摩托车", value: "MOTORBIKE" },
  { label: "电动车", value: "ELECTRIC" },
];

const handleRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        console.log("开始骑手注册请求");
        
        // 验证车辆类型不为空
        if (!registerForm.vehicleType) {
          ElMessage.error("请选择车辆类型");
          return;
        }
        
        const registerData = {
          realName: registerForm.realName,
          idCard: registerForm.idCard,
          idCardFront: registerForm.idCardFront,
          idCardBack: registerForm.idCardBack,
          vehicleType: registerForm.vehicleType as VehicleType,
          vehicleNumber: registerForm.vehicleNumber,
          password: registerForm.password,
        };

        const res = await riderApi.register(registerData);
        
        console.log("注册响应:", res);

        if (res.status === 200) {
          ElMessage({
            message: "注册成功，请等待审核",
            type: "success",
            duration: 3000,
          });
          
          setTimeout(() => {
            router.push("/rider/login");
          }, 1000);
        } else {
          ElMessage.error("注册失败，请重试");
        }
      } catch (e) {
        console.error("注册接口异常：", e);
        ElMessage.error("网络错误或服务器异常");
      } finally {
        loading.value = false;
      }
    }
  });
};

const goToLogin = () => {
  router.push("/rider/login");
};

const goBack = () => {
  router.push("/rider/login");
};

// 处理身份证照片上传
const handleIdCardUpload = (type: 'front' | 'back') => {
  // TODO: 实现图片上传逻辑
  ElMessage.info(`请上传身份证${type === 'front' ? '正面' : '反面'}照片`);
};
</script>

<template>
  <div class="register-container">
    <div class="tech-bg"></div>
    <div class="register-box">
      <el-button
        icon="Back"
        circle
        @click="goBack"
        class="back-btn"
      ></el-button>
      <div class="register-header">
        <h2>
          骑手注册
          <span class="en-title">Rider Register</span>
        </h2>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-position="top"
        class="register-form"
        @keyup.enter="handleRegister(registerFormRef)"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            prefix-icon="User"
            class="tech-input"
            clearable
            autocomplete="username"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            prefix-icon="Lock"
            show-password
            class="tech-input"
            maxlength="18"
            autocomplete="new-password"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            prefix-icon="Lock"
            show-password
            class="tech-input"
            maxlength="18"
            autocomplete="new-password"
          />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="registerForm.realName"
            prefix-icon="User"
            class="tech-input"
            maxlength="10"
          />
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="registerForm.idCard"
            prefix-icon="CreditCard"
            class="tech-input"
            maxlength="18"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            prefix-icon="Phone"
            class="tech-input"
            maxlength="11"
            autocomplete="tel"
          />
        </el-form-item>

        <el-form-item label="配送工具" prop="vehicleType">
          <el-select
            v-model="registerForm.vehicleType"
            placeholder="请选择配送工具"
            class="tech-input"
            style="width: 100%"
          >
            <el-option
              v-for="item in vehicleTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="车辆牌照" prop="vehicleNumber">
          <el-input
            v-model="registerForm.vehicleNumber"
            prefix-icon="Bicycle"
            class="tech-input"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="身份证照片">
          <div class="id-card-upload">
            <div class="upload-item">
              <span>身份证正面</span>
              <el-button @click="handleIdCardUpload('front')" size="small">
                上传照片
              </el-button>
            </div>
            <div class="upload-item">
              <span>身份证反面</span>
              <el-button @click="handleIdCardUpload('back')" size="small">
                上传照片
              </el-button>
            </div>
          </div>
        </el-form-item>

        <div class="form-actions">
          <el-button
            type="primary"
            @click="handleRegister(registerFormRef)"
            :loading="loading"
            class="register-btn"
          >
            注册
          </el-button>
        </div>

        <div class="form-links">
          <el-link @click="goToLogin">已有账号？点击登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
@import url("https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@500&display=swap");

.register-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: linear-gradient(
      rgba(255, 224, 130, 0.82),
      rgba(255, 213, 79, 0.82)
    ),
    url("https://images.pexels.com/photos/70497/pexels-photo-70497.jpeg?auto=compress&w=900&q=80")
      center center/cover no-repeat;
  color: #222;
  font-family: "Noto Serif SC", "阿里巴巴普惠体", "思源宋体", "微软雅黑",
    "Microsoft YaHei", Arial, sans-serif;
}

.register-box {
  z-index: 1;
  width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  padding: 2.5rem 2.5rem 2rem 2.5rem;
  background: rgba(255, 245, 200, 0.97);
  border-radius: 24px;
  box-shadow: 0 4px 24px 0 #90caf933;
  border: 2.5px solid #90caf9;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  color: #a05a1c;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .register-box {
    width: 90%;
    max-width: 450px;
    max-height: 95vh;
    padding: 2rem 1.5rem 1.5rem 1.5rem;
    border-radius: 20px;
    margin: 1rem;
  }
}

@media (max-width: 480px) {
  .register-box {
    width: 95%;
    max-width: 380px;
    max-height: 98vh;
    padding: 1.5rem 1rem 1rem 1rem;
    border-radius: 16px;
    margin: 0.5rem;
    border-width: 2px;
  }
}

.register-header {
  position: relative;
  text-align: center;
  margin-bottom: 2rem;
}

@media (max-width: 480px) {
  .register-header {
    margin-bottom: 1.5rem;
  }
}

.register-header h2 {
  font-size: 2rem;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  color: #d2691e;
  letter-spacing: 0.08em;
  margin-bottom: 0.2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

@media (max-width: 768px) {
  .register-header h2 {
    font-size: 1.75rem;
  }
}

@media (max-width: 480px) {
  .register-header h2 {
    font-size: 1.5rem;
    letter-spacing: 0.05em;
  }
}

.register-header .en-title {
  font-size: 1rem;
  color: #bfa16b;
  font-family: "PingFang SC", Arial, sans-serif;
  margin-top: 0.1rem;
  letter-spacing: 0.12em;
  opacity: 0.85;
}

@media (max-width: 480px) {
  .register-header .en-title {
    font-size: 0.9rem;
    letter-spacing: 0.08em;
  }
}

.back-btn {
  position: absolute;
  left: 0.8rem;
  top: 0.8rem;
  z-index: 2;
}

.register-form {
  margin-top: 1.5rem;
  width: 100%;
  color: #a05a1c;
}

.el-form-item__label {
  color: #ff9800;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.tech-input :deep(.el-input__wrapper) {
  background: #fffbe8;
  border: 1.5px solid #ffd600;
  border-radius: 14px;
  box-shadow: 0 2px 8px 0 #ffd60022;
  color: #222;
  font-size: 1.1rem;
  transition: border-color 0.3s, box-shadow 0.3s;
}

.tech-input :deep(.el-input__wrapper):focus-within {
  border-color: #ff9800;
  box-shadow: 0 0 0 2px #ffd60099, 0 0 12px 2px #ff980055;
}

.tech-input :deep(.el-input__inner) {
  background: transparent;
  color: #222;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.tech-input :deep(.el-select__wrapper) {
  background: #fffbe8;
  border: 1.5px solid #ffd600;
  border-radius: 14px;
  box-shadow: 0 2px 8px 0 #ffd60022;
}

.id-card-upload {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.upload-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #fffbe8;
  border: 1px solid #ffd600;
  border-radius: 8px;
}

.form-actions {
  margin-top: 1.5rem;
}

.register-btn {
  width: 100%;
  font-size: 1.1rem;
  background: linear-gradient(90deg, #fff700 0%, #ffd600 60%, #ff9800 100%);
  border: none;
  color: #fff;
  font-family: "PingFang SC", Arial, sans-serif;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 #ffd60055, 0 0 0 0 #fff;
  transition: background 0.3s, color 0.3s, box-shadow 0.3s;
  font-weight: 700;
  position: relative;
  overflow: hidden;
}

.register-btn::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  border-radius: 16px;
  background: linear-gradient(120deg, #fff 0%, transparent 80%);
  opacity: 0.18;
  pointer-events: none;
}

.register-btn:hover {
  background: linear-gradient(90deg, #fff700 0%, #ff9800 100%);
  color: #fffbe8;
  box-shadow: 0 4px 24px 0 #ffd60099, 0 0 0 0 #fff;
}

.form-links {
  margin-top: 1rem;
  text-align: center;
  color: #a05a1c;
}

.tech-bg {
  position: absolute;
  z-index: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
}

/* 移动端表单优化 */
@media (max-width: 768px) {
  .register-container {
    padding: 1rem 0;
  }
  
  .upload-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .upload-item span {
    font-size: 0.9rem;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 0.5rem 0;
    align-items: flex-start;
  }
  
  .register-box {
    margin-top: 0.5rem;
  }
  
  .tech-input :deep(.el-input__wrapper) {
    font-size: 1rem;
    border-radius: 12px;
  }
  
  .register-btn {
    font-size: 1rem;
    border-radius: 14px;
  }
  
  .upload-item {
    padding: 8px;
    border-radius: 6px;
  }
  
  .upload-item span {
    font-size: 0.85rem;
  }
  
  .el-button--small {
    font-size: 0.8rem;
    padding: 4px 8px;
  }
}
</style>
